<template>
    <div>
        <el-upload :action=dataObj.host ref="uploads" :data="dataObj" :list-type="listType" :file-list="fileList"
            :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess"
            :on-preview="handlePreview" :limit="maxCount" :on-exceed="handleExceed" :show-file-list="showFile"
            :auto-upload="false" :on-change="onChange" multiple>
            <i class="el-icon-plus"></i>
        </el-upload>

        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
    </div>
</template>
  <!--  -->
<script>

import { policy } from './policy'
import getUUID from '../../utils/uuid'


export default {
    name: "multiUpload",
    props: {
        //图片属性数组
        value: Array,
        //最大上传图片数量
        maxCount: {
            type: Number,
            default: 7
        },
        listType: {
            type: String,
            default: "picture-card"
        },
        showFile: {
            type: Boolean,
            default: true
        },
        master: {
            default: ''
        }
    },
    data() {
        return {
            dataObj: {
                policy: "",
                signature: "",
                key: "",
                ossaccessKeyId: "",
                dir: "",
                host: "",
                uuid: ""
            },
            dialogVisible: false,
            dialogImageUrl: null,
            fileCount: 0,
            beginCount: 0,

        };
    },
    computed: {
        // 初始化，从父组件传过来的数据
        fileList() {
            let fileList = [];
            for (let i = 0; i < this.value.length; i++) {
                let name = this.value[i].name
                let url = this.value[i].url
                fileList.push({
                    name: name,
                    url: url,
                    status: 'success'
                });
            }
            return fileList;
        },


    },
    watch: {
        master: {
            // 轮询进行判断是否上传结束
            handler(val, oldVal){
                this.handlers()
            },
            deep: true
        }
    },
    mounted() {
        this.$emit("beginUpload", this.$refs.uploads)
    },
    methods: {

        // 轮询判断
        handlers(val, oldVal) {
                setTimeout(() => {
                    if (this.beginCount == 0) {
                        this.emitInput(this.fileList);
                        // console.log('轮询结束')
                        return;
                    }
                    handlers(val, oldVal)
                    // console.log('轮询进行中')
                }, 500);
            },


        // 文件移除，触发
        handleRemove(file, fileList) {
            // 删除fileList
            if (this.fileList.length > 0) {
                for (let i = 0; i < this.fileList.length; i++) {
                    if (this.fileList[i].name == file.name) {
                        this.fileList.splice(i, 1);
                        break;
                    }
                }
            }
        },

        // 点击正在上传的文件时触发该事件 
        handlePreview(file) {
            this.dialogVisible = true;
            this.dialogImageUrl = file.url;
        },

        // 每次上传文件前 ，上传前请求事件钩子
        beforeUpload(file) {
            let _self = this;
            return new Promise((resolve, reject) => {
                policy()
                    .then(response => {
                        // console.log("begin upload the img ");
                        _self.dataObj.policy = response.data.policy;
                        _self.dataObj.signature = response.data.signature;
                        _self.dataObj.ossaccessKeyId = response.data.accessId;
                        _self.dataObj.key = response.data.dir + getUUID() + "_${filename}";
                        _self.dataObj.dir = response.data.dir;
                        _self.dataObj.host = response.data.host;
                        this.fileList.push({
                            name: file.name,
                            url: this.dataObj.host + "/" + this.dataObj.key.replace("${filename}", file.name),
                        });
                        resolve(true);
                    })
                    .catch(err => {
                        // console.log("出错了...", err)
                        reject(false);
                    });
            });
        },

        // 图片上传成功后调用
        handleUploadSuccess(res, file) {
            // 添加数据
                
        },

        onChange(file, fileList) {
            // 文件为读时候，计数添加1
            if (file.status == 'ready') {
                this.beginCount += 1;
                // 文件上传成功时，计数--，如果为0，那么上传完毕，进n数据提交
            } else if (file.status == 'success') {
                this.beginCount -= 1;
                if (this.beginCount == 0) {
                    // 数据提交
                    this.emitInput(this.fileList)
                }
            }
        },



        // 将上传的图片url返回给父组件
        emitInput(fileList) {
            let value = [];
            for (let i = 0; i < fileList.length; i++) {
                value.push(fileList[i].url);
            }
            this.$emit("input", value);
            this.$emit("beginUpload", this.$refs.uploads)
        },


        // 图片超出处理
        handleExceed(files, fileList) {
            this.$message({
                message: "最多只能上传" + this.maxCount + "张图片",
                type: "warning",
                duration: 1000
            });
        }

    },

};
</script>
<style></style>
  
  
  